from fastapi import FastAPI, Request, Form, Depends
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from starlette.status import HTTP_302_FOUND

app = FastAPI()
templates = Jinja2Templates(directory="templates")

# 模拟数据库中的用户数据（实际项目请使用数据库）
fake_users_db = {
    "admin": {
        "username": "admin",
        "password": "admin123",  # 生产环境应存储哈希值
        "disabled": False
    }
}


def verify_user(username: str, password: str):
    """验证用户凭证"""
    user = fake_users_db.get(username)
    if not user:
        return False
    if user["password"] != password:
        return False
    return True


@app.get("/", response_class=HTMLResponse)
async def login_page(request: Request):
    """显示登录页面"""
    return templates.TemplateResponse("login.html", {"request": request})


@app.post("/login")
async def login_action(
        request: Request,
        username: str = Form(...),
        password: str = Form(...)
):
    """处理登录请求"""
    if verify_user(username, password):
        # 登录成功重定向到欢迎页
        return RedirectResponse("/welcome", status_code=HTTP_302_FOUND)

    # 登录失败显示错误信息
    return templates.TemplateResponse(
        "login.html",
        {"request": request, "error": "Invalid credentials"},
        status_code=401
    )


@app.get("/welcome", response_class=HTMLResponse)
async def welcome_page(request: Request):
    """欢迎页面"""
    return HTMLResponse("""
        <h1 style="color: green">Login Success!</h1>
        <p>Welcome to the system</p>
    """)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)